﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WCSY.MODEL;
using System.Data;
using WCSY.BLL;

public partial class CostsManagement_costsOther : System.Web.UI.Page
{
    Fg_deptInfoManager deptM = new Fg_deptInfoManager();
    Fg_empInfoManager empM = new Fg_empInfoManager();
    fg_costsManager costM = new fg_costsManager();
    wcsy_costsOtherOrderMstManager othermstM = new wcsy_costsOtherOrderMstManager();
    wcsy_costsOtherOrderDetManager otherdetM = new wcsy_costsOtherOrderDetManager();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if(Request["sysno"] != null){
                pageFlag.Value = Request["sysno"];
            }
            if (pageFlag.Value != null && !pageFlag.Value.Equals(""))
            {
                string sysno = Request["sysno"].ToString();
                //初始主表
                DataTable othermst = othermstM.GetAllListByPara(sysno,"0","","","","").Tables[0];
                txtfilldate.Text = Convert.ToDateTime(othermst.Rows[0]["filldate"]).ToShortDateString();
                txtsysNo.Text = sysno;
                txtinsideNo.Text = othermst.Rows[0]["insideNo"].ToString();
                txtbusinessDate.Text = Convert.ToDateTime(othermst.Rows[0]["businessDate"]).ToShortDateString();
                //绑定申请部门
                DataTable deptList = deptM.GetAllList().Tables[0];
                this.ddlapplyDept.DataSource = deptList;
                this.ddlapplyDept.DataTextField = "deptname";
                this.ddlapplyDept.DataValueField = "id";
                this.ddlapplyDept.DataBind();
                ListItem sec = new ListItem();
                sec.Text = "-请选择-";
                sec.Value = "0";
                ddlapplyDept.Items.Insert(0, sec);
                ddlapplyDept.SelectedValue = othermst.Rows[0]["deptNo"].ToString();
                //绑定申请人
                string deptno = othermst.Rows[0]["deptNo"].ToString();
                DataSet empList = empM.GetList(" DeptNo = '" + deptno + "'");
                this.ddlapplyPsn.DataSource = empList;
                this.ddlapplyPsn.DataTextField = "empname";
                this.ddlapplyPsn.DataValueField = "id";
                this.ddlapplyPsn.DataBind();
                if (!othermst.Rows[0]["applypsnNo"].Equals(""))
                {
                    ddlapplyPsn.SelectedValue = othermst.Rows[0]["applypsnNo"].ToString();
                }
                //绑定结算方式
                //绑定币种
                txtrate.Text = othermst.Rows[0]["rate"].ToString();
                txtloanNo.Text = othermst.Rows[0]["loanNo"].ToString();
                txtloanMoney.Text = othermst.Rows[0]["loanMoney"].ToString();
                txtpayMoney.Text = othermst.Rows[0]["payMoney"].ToString();
                txtattachNum.Text = othermst.Rows[0]["attachNum"].ToString();
                txtremarks.Text = othermst.Rows[0]["remarks"].ToString();
                //this.lblSumAppMoney.Text = othermst.Rows[0]["locsum"].ToString();
                
                //foreach (RepeaterItem item in costorderdetRepeater.Controls)
                //{
                //    if (item.ItemType == ListItemType.Footer)
                //    {
                //        Label sumLabel = (Label)item.FindControl("lblSumAppMoney");

                //        sumLabel.Text = othermst.Rows[0]["locsum"].ToString();

                //        break;
                //    }
                //}
                //初始明细表
                DataTable detlist = otherdetM.GetAllList().Tables[0];
                int upCount = detlist.Rows.Count;
                this.HiddenField1.Value = detlist.Rows.Count.ToString();
                for (int i = upCount; i < 10;i++)
                {
                    DataRow dr = detlist.NewRow();
                    dr["lineid"] = i + 1;
                    detlist.Rows.Add(dr);
                }
                this.costorderdetRepeater.DataSource = detlist;
                this.costorderdetRepeater.DataBind();
                ((Label)costorderdetRepeater.Controls[costorderdetRepeater.Controls.Count - 1].FindControl("lblSumAppMoney")).Text = othermst.Rows[0]["locsum"].ToString();
                setInitUpdCtrolsState();//以修改状态进入
                
            }
            else
            {//新增状态
                //初始主表
                txtfilldate.Text = DateTime.Now.ToShortDateString();
                txtsysNo.Text = tool.GetMaxSysno("sysno", "wcsy_costsOtherOrderMst");

                //检测是否获取到登录信息
                if (Session["userSysId"] != null)
                {
                    lblfillpsn.Text = Session["userName"].ToString();
                }
                else
                {
                    RegisterStartupScript("check", "<script>chkLogin()</script>");
                }
                //绑定申请部门
                DataTable deptList = deptM.GetAllList().Tables[0];
                this.ddlapplyDept.DataSource = deptList;
                this.ddlapplyDept.DataTextField = "deptname";
                this.ddlapplyDept.DataValueField = "id";
                this.ddlapplyDept.DataBind();
                ListItem sec = new ListItem();
                sec.Text = "-请选择-";
                sec.Value = "0";
                ddlapplyDept.Items.Insert(0, sec);


                //绑定结算方式
                //绑定币种

                //初始化明细表
                List<wcsy_costsOtherOrderDet> detlist = tool.GetOtherOrderDetData();
                this.costorderdetRepeater.DataSource = detlist;
                this.costorderdetRepeater.DataBind();
                setInitAddCtrolsState();
            }
        }
    }
    //保存数据
    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<string> sqlList = new List<string>();
        if (Request["sysno"] != null) //修改状态
        {
            string sysno = Request["sysno"].ToString();
            #region 修改主表数据
            try
            {
                wcsy_costsOtherOrderMst othermst = new wcsy_costsOtherOrderMst();
                othermst.sysNo = sysno;
                othermst.insideNo = txtinsideNo.Text;
                othermst.businessDate = Convert.ToDateTime(txtbusinessDate.Text);
                othermst.filldate = DateTime.Now;
                othermst.deptNo = ddlapplyDept.SelectedValue;
                othermst.applypsnNo = ddlapplyPsn.SelectedValue;
                othermst.accwayNo = ddlaccWay.SelectedValue;
                othermst.currencyNo = ddlcurrency.SelectedValue;
                othermst.rate = Convert.ToDecimal(txtrate.Text.Equals("") ? "0" : txtrate.Text);
                othermst.loanNo = txtloanNo.Text;
                othermst.loanMoney = tool.ToDecimal(txtloanMoney.Text);
                othermst.payMoney = tool.ToDecimal(txtpayMoney.Text);
                othermst.attachNum = tool.ToInt(txtattachNum.Text);
                othermst.remarks = txtremarks.Text;
                othermst.fillpsn = lblfillpsn.Text;
                sqlList.Add(othermstM.Update(othermst));
            }
            catch (Exception ex)
            {
                tool.Alert("表头信息保存失败！" + ex.Message, this);
                return;
            }
            #endregion
            //删除明细行数据
            sqlList.Add(otherdetM.Delete(sysno));
            #region 保存明细数据
            try
            {
                for (int i = 0; i < Convert.ToInt32(this.HiddenField1.Value); i++)
                {
                    wcsy_costsOtherOrderDet otherdet = new wcsy_costsOtherOrderDet();
                    otherdet.sysno = sysno;
                    otherdet.lineid = tool.ToInt(((Label)costorderdetRepeater.Items[i].FindControl("txtLineId")).Text);
                    otherdet.costsid = ((DropDownList)costorderdetRepeater.Items[i].FindControl("ddlcostsName")).SelectedValue;
                    if (otherdet.costsid.Equals("0"))
                    {
                        continue;
                    }
                    otherdet.discrip = ((TextBox)costorderdetRepeater.Items[i].FindControl("txtdescrip")).Text;
                    otherdet.applyMoney = tool.ToDecimal(((TextBox)costorderdetRepeater.Items[i].FindControl("txtapplyMoney")).Text);
                    if (otherdet.applyMoney == 0)
                    {
                        tool.Alert("第 " + otherdet.lineid.ToString() + " 行申请金额不能为0或为空！请填写！", this);
                        return;
                    }
                    otherdet.remarks = ((TextBox)costorderdetRepeater.Items[i].FindControl("txtdetremarks")).Text;
                    sqlList.Add(otherdetM.Add(otherdet));
                }
            }
            catch (Exception ex)
            {
                tool.Alert("表体信息保存失败！" + ex.Message, this);
                return;
            }
            #endregion
            #region 执行语句
            try
            {
                string suc = tool.executeSqlTran(sqlList);
                if (!suc.Equals("suc"))
                {
                    throw new Exception(suc);
                }
            }
            catch (Exception ex)
            {
                tool.Alert("信息保存失败！" + ex.Message, this);
                return;
            }

            tool.Alert("信息保存成功!", this);
            #endregion
            #region 设置按钮状态
            setAfterSaveCtrolsState();
            #endregion

        }
        else //新增状态
        {
            string sysno = tool.GetMaxSysno("sysno", "wcsy_costsOtherOrderMst");
            #region 保存主表数据
            try
            {
                wcsy_costsOtherOrderMst othermst = new wcsy_costsOtherOrderMst();
                othermst.sysNo = sysno;
                othermst.insideNo = txtinsideNo.Text;
                othermst.businessDate = Convert.ToDateTime(txtbusinessDate.Text);
                othermst.filldate = DateTime.Now;
                othermst.deptNo = ddlapplyDept.SelectedValue;
                othermst.applypsnNo = ddlapplyPsn.SelectedValue;
                othermst.accwayNo = ddlaccWay.SelectedValue;
                othermst.currencyNo = ddlcurrency.SelectedValue;
                othermst.rate = Convert.ToDecimal(txtrate.Text.Equals("") ? "0" : txtrate.Text);
                othermst.loanNo = txtloanNo.Text;
                othermst.loanMoney = tool.ToDecimal(txtloanMoney.Text);
                othermst.payMoney = tool.ToDecimal(txtpayMoney.Text);
                othermst.attachNum = tool.ToInt(txtattachNum.Text);
                othermst.remarks = txtremarks.Text;
                othermst.fillpsn = lblfillpsn.Text;
                sqlList.Add(othermstM.Add(othermst));
            }
            catch (Exception ex)
            {
                tool.Alert("表头信息保存失败！" + ex.Message, this);
                return;
            }
            #endregion
            #region 保存明细数据
            try
            {
                for (int i = 0; i < Convert.ToInt32(this.HiddenField1.Value); i++)
                {
                    wcsy_costsOtherOrderDet otherdet = new wcsy_costsOtherOrderDet();
                    otherdet.sysno = sysno;
                    otherdet.lineid = tool.ToInt(((Label)costorderdetRepeater.Items[i].FindControl("txtLineId")).Text);
                    otherdet.costsid = ((DropDownList)costorderdetRepeater.Items[i].FindControl("ddlcostsName")).SelectedValue;
                    if (otherdet.costsid.Equals("0"))
                    {
                        continue;
                    }
                    otherdet.discrip = ((TextBox)costorderdetRepeater.Items[i].FindControl("txtdescrip")).Text;
                    otherdet.applyMoney = tool.ToDecimal(((TextBox)costorderdetRepeater.Items[i].FindControl("txtapplyMoney")).Text);
                    if (otherdet.applyMoney == 0)
                    {
                        tool.Alert("第 " + otherdet.lineid.ToString() + " 行申请金额不能为0或为空！请填写！", this);
                        return;
                    }
                    otherdet.remarks = ((TextBox)costorderdetRepeater.Items[i].FindControl("txtdetremarks")).Text;
                    sqlList.Add(otherdetM.Add(otherdet));
                }
            }
            catch (Exception ex)
            {
                tool.Alert("表体信息保存失败！" + ex.Message, this);
                return;
            }
            #endregion
            #region 执行语句
            try
            {
                string suc = tool.executeSqlTran(sqlList);
                if (!suc.Equals("suc"))
                {
                    throw new Exception(suc);
                }
            }
            catch (Exception ex)
            {
                tool.Alert("信息保存失败！" + ex.Message, this);
                return;
            }

            tool.Alert("信息保存成功!", this);
            #endregion
            #region 设置按钮状态
            setAfterSaveCtrolsState();
            #endregion
        }
    }

    /// <summary>
    /// 设置初始进入（新增状态），按钮及控件状态
    /// </summary>
    public void setInitAddCtrolsState()
    {
        //设置保存按钮不可用
        btnUpd.Enabled = false;
        btnDel.Enabled = false;
        btnSave.Enabled = true;
        
        
        //设置控件为只读状态
        tool.SetControlReadOnly(txtsysNo);
        tool.SetControlReadOnly(txtfilldate);
    }
    /// <summary>
    /// 设置初始进入（修改状态），按钮及控件状态
    /// </summary>
    public void setInitUpdCtrolsState() {
        //设置保存按钮不可用
        btnSave.Enabled = false;
        btnUpd.Enabled = true;
        btnDel.Enabled = true;
        //设置控件为只读状态
        tool.SetControlReadOnly(this);
    }
    /// <summary>
    /// 保存完毕后，设置按钮状态
    /// </summary>
    public void setAfterSaveCtrolsState() {
        //设置保存按钮不可用
        btnSave.Enabled = false;
        btnUpd.Enabled = true;
        btnDel.Enabled = true;
        //设置控件为只读状态
        tool.SetControlReadOnly(this);
        
    }
    /// <summary>
    /// 修改完毕后，设置按钮状态
    /// </summary>
    public void setAfterUpdCtrolsState() {
        btnUpd.Enabled = false;
        btnDel.Enabled = false;
        btnSave.Enabled = true;
        tool.SetControlReadOnlyNone(this);
        tool.SetControlReadOnly(txtsysNo);
        tool.SetControlReadOnly(txtfilldate);
        pageFlag.Value = txtsysNo.Text;
        
    }
    //部门发生变化，填充申请人
    protected void ddlapplyDept_SelectedIndexChanged(object sender, EventArgs e)
    {
        //绑定申请人
        string deptno = ddlapplyDept.SelectedValue;
        DataSet empList = empM.GetList(" DeptNo = '" + deptno + "'");
        this.ddlapplyPsn.DataSource = empList;
        this.ddlapplyPsn.DataTextField = "empname";
        this.ddlapplyPsn.DataValueField = "id";
        this.ddlapplyPsn.DataBind();
        
    }
    protected void costorderdetRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
            DropDownList ddlcostsName = e.Item.FindControl("ddlcostsName") as DropDownList;
            //ddlcostsName.DataSource = costM.GetAllList().Tables[0];
            //ddlcostsName.DataTextField = "name";
            //ddlcostsName.DataValueField = "id";
            //ddlcostsName.DataBind();
            //ListItem sec = new ListItem();
            //sec.Text = "-选择-";
            //sec.Value = "0";
            //ddlcostsName.Items.Insert(0, sec);
            string costsid = (e.Item.FindControl("txtcostsName") as TextBox).Text;
            ddlcostsName.SelectedValue = costsid;

            }
    }
    //点击修改按钮，变更按钮状态
    protected void btnUpd_Click(object sender, EventArgs e)
    {
        setAfterUpdCtrolsState();
    }
}
